package probe.logic;

import java.util.ArrayList;

public class Update {

	private Task _task;
	private ArrayList<Task> _updateList;
	private String _message;
	private Add _doAdd;
	private int _updateType;
	private String [] _updateDetails;
	
	private static final int TASKNAME_INDEX= 0;
	private static final int FIRST_UPDATE_PARAMETER = 1;
	private static final int MIN_REQUIRED_PARAMETERS = 1;
	
	private static final int UPDATE_BY_STATUS = 1;
	private static final int UPDATE_BY_TIME_DATE = 2;
	
	private static final String STATUS_DONE = "DONE";
	private static final String STATUS_UNFINISHED = "UNFINISHED";
	
	private static final String ERROR_MESSAGE_1 = "The task cannot be found!";
	
	public Update() {
		_task = new Task();
		_message = null;
		_doAdd = new Add();
		_updateList = new ArrayList<Task>();
	}
	
	private void initialise() {
		_task = new Task();
		_message = null;
		_doAdd = new Add();
		_updateList = new ArrayList<Task>();
	}
	
	private Task findTask(String name) {
		
		for(int i = 0; i < _updateList.size(); i++) {
			Task task = _updateList.get(i);
			if(task.taskName.equalsIgnoreCase(name)) {
				_updateList.remove(i);
				return task;
			}
		}
		
		return null;
	}
	
	private void identifyUpdateType() {
		if(_updateDetails.length == MIN_REQUIRED_PARAMETERS) {
			_updateType = UPDATE_BY_TIME_DATE;
		} else {
			if(_updateDetails[FIRST_UPDATE_PARAMETER].equals(STATUS_DONE) || _updateDetails[FIRST_UPDATE_PARAMETER].equals(STATUS_UNFINISHED)) {
				_updateType =  UPDATE_BY_STATUS;
			} else {
				_updateType = UPDATE_BY_TIME_DATE;
			}
		}
		
	}

	private void updateByStatus() {
		if(_updateDetails[FIRST_UPDATE_PARAMETER].equals(STATUS_DONE)) {
			_task.taskStatus = Task.TaskStatus.DONE;
		} else {
			_task.taskStatus = Task.TaskStatus.UNFINISHED;
		}
		
		_updateList.add(_task);
	}
	
	private void doUpdate() {
		
		if(_updateType == UPDATE_BY_STATUS) {
			updateByStatus();
		} else {
			_updateList = _doAdd.process(_updateList, _updateDetails);
			_message = _doAdd.getMessage();
		}
		
	}
	
	public String getMessage() {
		return _message;
	}
		
	public ArrayList<Task> process (ArrayList<Task> list, String [] commandDetails) {
		
		initialise();
		_updateList = list;
		_updateDetails = commandDetails;
		_task = findTask(commandDetails[TASKNAME_INDEX]);
		if(_task==null) {
			_message = ERROR_MESSAGE_1;
			return _updateList;
		}
		
		identifyUpdateType();
		doUpdate();
		return _updateList;
	}
}
